package cn.edu.hznu.util.socket.udp;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Client {
	public static void main(String[] args) {
		String strSend = "Hello UDPserver";
		byte[] buf = new byte[1024];
		try {
			DatagramSocket ds = new DatagramSocket(9000);
			InetAddress loc = InetAddress.getLocalHost();
			DatagramPacket dpSend = new DatagramPacket(strSend.getBytes(), strSend.length(), loc, 3000);
			DatagramPacket dpReceive = new DatagramPacket(buf, 1024);
			ds.setSoTimeout(5000);
			int tries = 0;
			boolean receivedResponse = false;
			while (!receivedResponse && tries < 5) {
				ds.send(dpSend);
				try {
					ds.receive(dpReceive);
					if (!dpReceive.getAddress().equals(loc)) {
						throw new IOException("Received packet from unknown source");
					}
					receivedResponse = true;
				} catch (InterruptedIOException e) {
					tries += 1;
					System.out.println("Time out," + (5 - tries) + " more tries");
				}
			}
			if (receivedResponse) {
				System.out.println("client received data from server");
				String strReceive = new String(dpReceive.getData(), 0, dpReceive.getLength())
						+ " from " + dpReceive.getAddress().getHostAddress() + ": " + dpReceive.getPort();
				System.out.println(strReceive);
				dpReceive.setLength(1024);
			} else {
				System.out.println("No response -- give up.");
			}
			ds.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
}
